{extend name="common/base"/}
<!-- 主体 -->
{block name="body"}
<style type="text/css">
	/* 拖拽时显示移动光标 */
.layui-layer-gougu-admin .layui-layer-content {
    cursor: move;
}

/* 拖拽过程阴影效果 */
.layui-layer-moving {
    box-shadow: 0 0 20px rgba(0,0,0,0.2);
}
.layui-layer-gougu-admin {
    transform: translateZ(0);
}
</style>
<div class="p-3">
	<form class="layui-form gg-form-bar border-t border-x">
		<!-- <div class="layui-input-inline" style="width:300px;">
			<input type="text" name="keywords" placeholder="请输入关键字" class="layui-input" autocomplete="off" />
		</div> -->
		<div class="layui-input-inline" style="width:200px;">
			<select name="region" id="region" lay-reqText="请选择县区" lay-search=""  lay-filter="region">
					<option value="">--选择县区-- </option>
					{volist name=":get_region()" id="v"}
					<option value="{$v.id}">{$v.nianji} </option>
					{/volist}
				</select>
		</div>
		<div class="layui-input-inline" style="width:200px;">
				<select name="sorting_admin"  lay-reqText="请选择分拣员" lay-search="">
					<option value="0" >--请选择分拣员-- </option>
					{volist name=":get_fenjian()" id="v"}
					<option value="{$v.id}">{$v.name} </option>
					{/volist}
				</select>
		</div>
		<div class="layui-input-inline" style="width:200px;">
			<input type="text" name="name" placeholder="商品名" class="layui-input" autocomplete="off" />
		</div>
		<div class="layui-input-inline" style="width:200px;">
			<input type="text" name="order_no" placeholder="订单号" class="layui-input" autocomplete="off" />
		</div>
		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="delivery_time1"   id="delivery_time1" autocomplete="off" placeholder="配送时间-开始" class="layui-input">
		</div>
		<div class="layui-input-inline" style="margin-left:20px">—</div>
		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="delivery_time2"   id="delivery_time2" autocomplete="off" placeholder="配送时间-结束" class="layui-input">
		</div>
		<div class="layui-input-inline">
		<button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="searchform">提交搜索</button>

		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="create_time1"   id="create_time1" autocomplete="off" placeholder="导入时间-开始" class="layui-input">
		</div>
		<div class="layui-input-inline" style="margin-left:20px">—</div>
		<div class="layui-input-inline" style="margin-left:20px;width:150px;">
			<input type="text" name="create_time2"   id="create_time2" autocomplete="off" placeholder="导入时间-结束" class="layui-input">
		</div>
		<div class="layui-input-inline">
		<button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="daochuexcel">导出今日分拣</button>
		</div>
		
		</div>
		<div class="sunhao" style="margin:10px"></div>
	</form>
	<table class="layui-hide" id="order" lay-filter="order"></table>
</div>
<div class="p-3">

</div>
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<!-- <span class="layui-btn layui-btn-sm" lay-event="add" data-title="添加订单表">+ 添加单条</span> -->
		
		<button class="layui-btn layui-btn-sm" lay-event="dayin" >批量热敏打印</button>
		<button class="layui-btn layui-btn-sm" lay-event="dayin2" >批量打印销货单</button>
		<button class="layui-btn layui-btn-sm" lay-event="dayin3" >批量打印加工单</button><br>
		<button class="layui-btn layui-btn-sm" lay-event="import" >批量导入</button>
		<button class="layui-btn layui-btn-sm" lay-event="edit_fenjian" >批量改分拣员</button>
		<button class="layui-btn layui-btn-sm" lay-event="pi_del" >批量删除</button>
		<button class="layui-btn layui-btn-sm" lay-event="dayin4" >批量复制</button>
		
	</div>
</script>

<script type="text/html" id="barDemo">

<div class="layui-btn-group">
	<!-- <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="read">查看</a> -->

	<!-- <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="dayin">热敏打印</a>
	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="dayin2">打印</a>
	<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="dayin3">加工单</a> -->
	<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</div>
</script>

{/block}
<!-- /主体 -->

<!-- 脚本 -->
{block name="script"}
<script>
	const moduleInit = ['tool'];
	
	if ('ontouchstart' in window) {
    obj.find('.layui-layer-content').on('touchmove', function(e) {
        e.preventDefault();
    });
}	
	function gouguInit() {
		var table = layui.table,tool = layui.tool, form = layui.form;
		//日期选择
		layui.laydate.render({
			elem: '#delivery_time1' //指定元素
		});
		//日期选择
		layui.laydate.render({
			elem: '#delivery_time2' //指定元素
		});
		layui.laydate.render({
			elem: '#create_time1',
	    type: 'datetime', // 只需选择日期
	    done: function(value) {
	        // 自动补全时间
	        this.elem.value = value + ' 00:00:00'; 
	    }
		});
		//日期选择
		layui.laydate.render({
			elem: '#create_time2', //指定元素
			type: 'datetime',
			format: 'yyyy-MM-dd 23:59:59' // 自动填充时间
		});
		layui.pageTable = table.render({
			elem: '#order',
			title: '订单表列表',
			toolbar: '#toolbarDemo', 
			url: '/admin/order/datalist',
			defaultToolbar: [],
			page: true,
			limit: 15,
			cellMinWidth: 80,
			/*cellMinWidth: 80,done: function(res) {
			    // 覆盖打印按钮行为
			    $('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			      customizePrint(res.data); // 调用自定义打印方法
			      return false; // 阻止默认打印
			    });
		  	},*/
		  	/*done: function(res) {
			    // 覆盖打印按钮行为
			    $('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			    	
			      printCustomColumns(res.data); // 调用自定义打印方法
			      return false; // 阻止默认打印
			    });
		  	},*/
		  	done: function(res) {
			  // 覆盖打印按钮行为
			  //$('.layui-table-tool .layui-btn[lay-event="LAYTABLE_PRINT"]').on('click', function() {
			  	//console.log(res);
			  	$(".sunhao").html(res.msg);
			  	$('.layui-table-tool .layui-icon-print').parent().on('click', function() {
			    printCustomColumns(res.data); // 调用自定义打印方法
			    return false; // 阻止默认行为
			  });
			},
			cols: [
				[
				{type: 'checkbox', fixed: 'left',
					printable: false},
				{
					fixed: 'left',
					field: 'id',
					title: '编号',
					align: 'center',
					width: 50,
					printable: false
				},{
					field: 'nianji',
					title: '县区',
					align: 'center',
					printable: true
				},{
					field: 'name',
					title: '商品名称',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'specification',
					title: '规格',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'total_items',
					title: '商品数',
					align: 'center',
					width: 60,
					printable: true
				},{
					field: 'purchaser',
					title: '采购方',
					align: 'center',
					width: 180,
					printable: true
				},{
					field: 'status',
					title: '状态',
					align: 'center',
					printable: false,
					width: 80,
				},{
					field: 'produced_time',
					title: '生产日期',
					align: 'center',
					width: 100,
					printable: true
				},{
					field: 'delivery_time',
					title: '配送日期',
					align: 'center',
					width: 100,
					printable: true
				},{
					field: 'sorting',
					title: '分拣量',
					align: 'center',
					printable: false,
					printable: true
				},{
					field: 'remark',
					title: '备注',
					align: 'center',
					printable: true
				},{
					field: 'order_no',
					title: '订单号',
					align: 'center',
					width: 130,
					printable: true
				},{
					field: 'sorting_admin',
					title: '分拣员',
					align: 'center'
				},{
					field: 'delivery_admin',
					title: '配送人',
					align: 'center',
					printable: true
				},{
					field: 'create_time',
					title: '导入时间',
					align: 'center',
					printable: false,
					width: 160,
				},
				{
					fixed: 'right',
					field: 'right',
					title: '操作',
					toolbar: '#barDemo',
					width: 180,
					align: 'center',
					printable: false
				}				
				]
			]
		});
		
		//监听表头工具栏事件
		table.on('toolbar(order)', function(obj){
			if (obj.event === 'add') {
				tool.side("/admin/order/add");
				return false;
			}
			if (obj.event === 'import') {
				tool.side("/admin/order/order_import");
				return false;
			}
			if (obj.event === 'dayin') {
				//批量删除
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }
        printremin(selectedData);
				//console.log(selectedData);
			}
			if (obj.event === 'dayin2') {
				//批量删除
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }
        print2(selectedData);
				//console.log(selectedData);
			}
			if (obj.event === 'dayin3') {
				//批量删除
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }
        print3(selectedData);
				//console.log(selectedData);
			}
			if (obj.event === 'edit_fenjian') {
				//批量修改分拣员
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }
        const orderIds = selectedData.map(item => item.order_no);
        console.log(orderIds);
        tool.side("/admin/order/edit_fenjian?order_no="+orderIds);
				return false;
			}
			if (obj.event === 'pi_del') {
				//批量删除
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }
        const order_nos = selectedData.map(item => item.order_no);
        console.log(order_nos);
        layer.confirm('确定要删除订单号为：'+order_nos+'的数据吗?', {
					icon: 3,
					title: '提示'
				}, function(index) {
					let callback = function (e) {
						layer.msg(e.msg);
						if (e.code == 0) {
							setTimeout(function () {
								parent.location.reload();
							}, 1000);		
							//obj.del();
						}
					}
					tool.delete("/admin/api/pi_del", { order_no: order_nos}, callback);
					layer.close(index);
				});
       //tool.side("/admin/order/edit_fenjian?order_no="+orderIds);
				return false;
			}
			if (obj.event === 'dayin4') {
				//批量删除
				// 1. 获取选中行数据
        var checkStatus = table.checkStatus('order'); // 'order'对应表格elem的ID
        var selectedData = checkStatus.data;
        // 2. 校验选中数据
        if (selectedData.length === 0) {
            layer.msg('请至少选择一条数据', { icon: 3 });
            return false;
        }

        const allGoods = selectedData.flatMap(order => order.goods);
				console.log(selectedData);
				// 生成带编号的格式化文本
    const clipboardText = allGoods.map((item, index) => {
        //return `${index + 1}\t${item.purchaser}\t${item.sorting}\t${item.remark}`;
        // 最终优化版（兼容性+健壮性）
return `${index + 1}\t${item.purchaser}\t${item.name}\t${item.remark}\t${Math.trunc(Number(item.sorting)) || 0}斤`;

    }).join('\n');

    // 添加表头
    const header = '编号\t采购方\t商品\t备注\t分拣量\n';
    const fullText = header + clipboardText;

    // 执行复制操作
    try {
        navigator.clipboard.writeText(fullText).then(() => {
            layer.msg(`已复制${selectedData.length}条数据`, { icon: 1 });
        });
    } catch (e) {
        // 兼容旧浏览器
        const textarea = document.createElement('textarea');
        textarea.value = fullText;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        layer.msg('数据已复制（旧版兼容模式）', { icon: 1 });
    }
				/*const clipboardText = formatClipboardText(selectedData);
        navigator.clipboard.writeText(clipboardText).then(() => {
            layer.msg(`成功复制${selectedData.length}条数据`, { icon: 1 });
        }).catch(err => {
            console.error('复制失败:', err);
            layer.msg('复制失败，请手动选择文本复制', { icon: 2 });
        });*/
			}
		});

		//监听表格行工具事件
		table.on('tool(order)', function(obj) {
			var data = obj.data;
			if (obj.event === 'read') {
				//tool.side('/admin/order/read?id='+obj.data.id);
				//tool.side('/admin/order/read?id='+obj.data.id);
				tool.side('/admin/order/read?order_no='+obj.data.order_no);
			}
			else if (obj.event === 'dayin') {
				printremin(data); 	
			}else if (obj.event === 'dayin2') {
				print2(data); 	
			}else if (obj.event === 'dayin3') {
				print3(data); 	
			}else if (obj.event === 'edit') {
				tool.side('/admin/order/edit?id='+obj.data.id);
				//tool.side('/admin/order/edit?order_no='+obj.data.order_no);
			}
			else if (obj.event === 'del') {
				layer.confirm('确定要删除该记录吗?', {
					icon: 3,
					title: '提示'
				}, function(index) {
					let callback = function (e) {
						layer.msg(e.msg);
						if (e.code == 0) {
							obj.del();
						}
					}
					tool.delete("/admin/order/del", { id: data.id }, callback);
					layer.close(index);
				});
			}
			return false;
		});

		//监听搜索提交
		
		form.on('submit(searchform)', function(data) {
			//console.log(data);
			layui.pageTable.reload({
				where: {
					name: data.field.name,
					region: data.field.region,
					order_no: data.field.order_no,
					sorting_admin: data.field.sorting_admin,
					delivery_time1: data.field.delivery_time1,
					delivery_time2: data.field.delivery_time2
				},
				page: {
					curr: 1
				}
			});
			return false;
		});
		form.on('submit(daochuexcel)', function(data) {
			location.href = '/admin/api/export?create_time1='+data.field.create_time1+'&create_time2='+data.field.create_time2+'&region='+data.field.region;
			/*$.ajax({
				url: "/admin/api/export",
				type: 'post',
				data: {
					create_time1:data.field.create_time1,
					create_time2:data.field.create_time2
				},
				success: function(e) {
					console.log(e);
					layer.msg('导出成功', { icon: 1 });
				}
			})	*/
			return false;
		});
		function printremin(dataList) {
			console.log(dataList);
    const styles = `
        <style>
            @media print {
                /* 严格匹配图片尺寸 */
                @page { 
                    size: 80mm 58mm !important;  /* 修正为正确标签尺寸 */
                    margin: 0mm 1mm 0mm 1mm !important; /* 上下边距清零 */
                }
                body {
						        page-break-inside: avoid !important;
						    }
                /* 主容器设置 */
                .gong_big {
                    width: 74mm !important;      /* 80-3 * 2=74 */
                    margin: 0 auto !important;
                    font-size: 10pt !important;  /* 适配图片字号 */
                    line-height: 1.2 !important;
                    padding: 0mm !important;     /* 清除所有内边距 */
                }

                /* LOGO与标题布局 */
                .logobase {
                    width: 8mm !important;     /* 匹配图片logo尺寸 */
                    height: 8mm !important;
                    margin: 0 auto  !important;
                }
                .logobase img {
                    width: 100% !important;
                    height: 100% !important;
                    object-fit: contain !important;
                }
                .gongsi_title{
                	font-size:12pt !important;    /* 原15pt过大 */
                    margin: 1mm 0 !important;     /* 控制间距 */
                }
                /* 内容区块 */
                .gong_big2 {
                    width: 98% !important;
                    margin: 0.5mm 0 !important;   /* 上下间距0.5mm */
                    padding: 0 !important;
                }
                .gong_big2:last-child {
								    page-break-after: avoid !important;
								}

                /* 中文换行策略 */
                .gong_right {
                		width: 98% !important;
                    word-break: break-all !important;
                    text-indent: -4.5mm !important;  
                    padding-left: 5mm !important;   /* 精确对齐图片文字起始位 */
                }
            }
        </style>
    `;
    const logoBase64 = logo();
    dataList.forEach(order => {
    		order.goods.forEach((goodsItem, index) => {
        const printWindow = window.open('', '_blank');
        const deliveryDate = new Date(goodsItem.delivery_time * 1000).toLocaleDateString();
        const content = `
            ${styles}
            <div class="gong_big">
                <div class="logobase">
                    <img src="${logoBase64}">
                </div>
                <div style="text-align:center" class="gongsi_title">山东汉达供应链管理有限公司</div>
                
                <!-- 动态内容 -->
                <div class="gong_big2">
                    <div class="gong_right">【订货单位】${goodsItem.purchaser}</div>
                </div>
                <div class="gong_big2">
                    <div class="gong_right">【食品名称】${goodsItem.name}</div>
                </div>
                <div class="gong_big2">
                    <div class="gong_right">【净含量】${goodsItem.sorting}斤</div>
                </div>
                <div class="gong_big2">
                    <div class="gong_right">【配送时间】${deliveryDate}</div>
                </div>
                <div class="gong_big2">
                    <div class="gong_right">【备注】${goodsItem.remark}</div>
                </div>
                <div class="gong_big2">
                    <div class="gong_right">【温馨提示】此单为配送业务出厂凭证,</br>当日有效,过期作废。</div>
                </div>
            </div>
        `;

        printWindow.document.write(content);
        printWindow.document.close();

        // 严格时序控制
        printWindow.onload = () => {
		        printWindow.print();
		        printWindow.close();
		        //setTimeout(() => printWindow.close(), 1000);
		    };
        /*printWindow.onload = () => {
            setTimeout(() => {  // 等待字体渲染
                printWindow.print();
                setTimeout(() => printWindow.close(), 1000);
            }, 300);
        };*/
		  })
    });
}
		// 自定义打印函数
function printremin20250401(dataList) {
	
	//58*80
	//logo();
	const logoBase64 = logo();
	dataList.forEach((data) => {
		let tableContent ='';
		
		
		tableContent = '<div class="gong_big"><div class="logobase"><img class="tupian" src="'+logoBase64+'"></div><div style="text-align:center">山东汉达供应链管理有限公司</div>'
		console.log(data);
    // 原有处理逻辑（需调整窗口管理）
    const printWindow = window.open("about:blank", "_blank");
    // 生成HTML内容...
    tableContent+='<div class="gong_big2"><div class="gong_right">【订货单位】'+data.purchaser+'</div></div>';
	  tableContent+='<div class="gong_big2"><div class="gong_right">【食品名称】'+data.name+'</div>';
	  tableContent+='<div class="gong_big2"><div class="gong_right">【净含量】'+data.sorting+'斤</div></div>';
	  tableContent+='<div class="gong_big2"><div class="gong_right">【配送时间】'+data.delivery_time+'</div></div>';
	  tableContent+='<div class="gong_big2"><div class="gong_right">【备注】'+data.remark+'</div></div>';
	  tableContent+='<div class="gong_big2"><div class="gong_right">【温馨提示】此单为配送业务</br>出厂凭证,当日有效,过期作废。</div></div></div>';
    

	  const styles = `
        <style>
            @media print {
                /* 重置所有继承样式 */
                .logobase, .gong_big, .gong_big2 {
                    all: initial !important; 
                }

                /* 精确控制LOGO尺寸 */
                .logobase {
                    width: 8mm !important;
                    height: 8mm !important;
                    margin: 2px auto !important;
                    display: block !important;
                }

                .logobase img {
                    width: 100% !important;
                    height: 100% !important;
                    object-fit: contain !important;
                }
                /* 热敏纸尺寸强制声明 */
                @page {
                    /*size: 80mm 70mm !important; */
                    size: 100mm 80mm !important; 
                    margin: 0 1mm !important;
                }
                /* 主容器控制 */
		            .gong_big {
		                width: 78mm !important;   /* 80mm - 2 * 3mm边距 */
		                margin: 0 auto !important;
		                font-size: 15pt !important;
		                padding-left:50mm !important;
		            }

		            /* 内容区块优化 */ 
		            .gong_big2 {
		                width: 78mm !important;  /* 防溢出 */
		                font-size: 12pt !important;
		                /*padding-left:1mm !important;*/
		            }
		            
		            /* 中文排版优化 */
		            .gong_right {
		            	/*width: 78mm !important;  防溢出 
		                letter-spacing: 0.5px !important;
		            	word-break: break-all !important; 
    overflow-wrap: anywhere !important;*/
		            }
                
            }
        </style>
    `;

	  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
	  printWindow.document.write(styles + tableContent);
	  printWindow.document.close();
	  /*printWindow.print();
  	printWindow.close();*/
		printWindow.onload = () => {
        printWindow.print();
        printWindow.close();
        //setTimeout(() => printWindow.close(), 1000);
    };

    // 添加延迟打印保证样式加载
    /*setTimeout(() => {
        printWindow.print();
        setTimeout(() => printWindow.close(), 1000);
    }, 500);*/

	
  });
  

	return false;


	
}
function print2(dataList) {
  //const printWindow = window.open("about:blank", "_blank");
  //let tableContent = '<div class="gong_big"><div style="text-align:center">山东汉达供应链管理有限公司</div>'

	dataList.forEach((data) => {
		const printWindow = window.open("about:blank", "_blank");
		const styles = `
    <style>
      @media print {
        body { 
          margin: 1cm;
          font-family: SimSun;
          -webkit-print-color-adjust: exact; 
        }
        .print-title { 
          font-size: 20px; 
          text-align: center;
          margin-bottom: 10px;
					margin-top:-40px;
        }
        .info-section { 
          margin-bottom: 5px;
          width: 100%;
					font-size: 12px; 
        }
        .info-section td { 
          padding: 5px 10px;
          border: 0px solid #000 !important; 
        }
        .goods-table {
          width: 100%;
          border-collapse: collapse;
          margin: 5px 0;
          page-break-inside: avoid;
					font-size:12px
        }
        .goods-table th, 
        .goods-table td {
          border: 1px solid #000;
          padding: 8px;
          text-align: center;
        }
        .signature-area {
          margin-top: 20px;
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 12px;
					font-size:12px;
        }
        .no-print { display: none; }
      }
    </style>
  `;
  	const safeData = {
    order_no: data.order_no || '',
    purchaser: data.purchaser || '',
    delivery_time: data.delivery_time || '',
    user: data.user || '',
    phone: data.phone || '',
    address: data.address || '',
    supplier_phone: data.supplier_phone || '',
    // 假设商品数据为数组
    goods: data.goods || [{
      name: '-',
      price: '0',
      produced_time: '-',
      sorting: '-',
      quantity: '-',
      remark: '-',
      order_quantity: '',
      allocation: ''
    }],
    total_amount: data.total_amount || ''
  };

  // 构建HTML结构（匹配图片布局）
  let content = `
    <div class="print-title">山东汉达供应链管理有限公司销货单</div>
    
    <!-- 头部信息表格 -->
    <table class="info-section" style="border:0">
      <tr >
        <td width="15%">订单号</td>
        <td width="40%">${safeData.order_no}</td>
        <td width="15%">购货单位</td>
        <td width="40%">${safeData.purchaser}</td>
      </tr>
      
      <tr>
        <td>配送时间</td>
        <td>${safeData.delivery_time}</td>
        <td>收货人</td>
        <td>${safeData.user} ${safeData.phone}</td>
      </tr>
      <tr>
        <td>配送地址</td>
        <td>${safeData.address}</td>
        <td>收货电话</td>
        <td>${safeData.phone}</td>
      </tr>
    </table>

    <!-- 商品明细表格 -->
    <table class="goods-table">
      <thead>
        <tr>
          <th>商品名称</th>
          <th>规格</th>
          <th>生产日期</th>
          <th>保质期(天)</th>
          <th>单价（元）</th>
          <th>下单量</th>
          <th>分拣量</th>
          <th>分拣合计</th>
          <th>客户备注</th>
        </tr>
      </thead>
      <tbody>
        ${safeData.goods.map(item => `
          <tr>
            <td>${item.name}</td>
            <td>${item.name}</td>

            <td>${item.produced_time===null ? '':item.produced_time}</td>
            <td>60</td>
            <td>${item.price===null ? '':item.price}</td>
            <td>${item.sorting===null ? '':item.sorting}</td>
            <td>${item.sorting===null ? '':item.sorting}</td>
            <td> ${(item.price===null ? '':item.price) * (item.sorting===null ? '':item.sorting)}</td>
            <td>${item.remark}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>

    <!-- 金额汇总 -->
    <div class="amount-section">
     <!--  <p>打印合计总额（元）：${safeData.total_amount}订单总额（元）：${safeData.total_amount}实配金额（元）：${safeData.total_amount}</p>-->
    </div>

    <!-- 签收区域 -->
    <div class="signature-area">
      <div>
        <!--<p>分拣员：${data.sorting_admin || '_'.repeat(8)}</p>-->
        <p>分拣员：_________</p>
        
      </div>
      <div>
        <p>验收人：_________</p>
      </div>
      <div>
        <p>配送员：${data.delivery_admin || '_'.repeat(8)}</p>
      </div>
    </div>
  `;

  printWindow.document.write(styles + content);
  printWindow.document.close();

  // 打印处理
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    setTimeout(() => printWindow.close(), 500);
  }

	})
  // 样式优化（适配图片布局）
  

  // 数据预处理（防止null值）
  
}
function print3(dataList) {
	dataList.forEach((data) => {
		const printWindow = window.open("about:blank", "_blank");
  
  
  // 样式优化（适配图片布局）
  const styles = `
    <style>
      @media print {
        body { 
          margin: 1cm;
          font-family: SimSun;
          -webkit-print-color-adjust: exact; 
        }
        .print-title { 
          font-size: 24px; 
          text-align: center;
          margin-bottom: 20px;
        }
        .info-section { 
          margin-bottom: 15px;
          width: 100%;
        }
        .info-section td { 
          padding: 5px 5px;
          border: 0px solid #000 !important; 
        }
        .goods-table {
          width: 100%;
          border-collapse: collapse;
          margin: 15px 0;
          page-break-inside: avoid;
        }
        .goods-table th, 
        .goods-table td {
          border: 1px solid #000;
          padding: 8px;
          text-align: center;
        }
        .signature-area {
          margin-top: 20px;
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
        }
        .no-print { display: none; }
      }
    </style>
  `;

  // 数据预处理（防止null值）
  const safeData = {
    order_no: data.order_no || '',
    purchaser: data.purchaser || '',
    delivery_time: data.delivery_time || '',
    user: data.user || '',
    phone: data.phone || '',
    address: data.address || '',
    supplier_phone: data.supplier_phone || '',
    // 假设商品数据为数组
    goods: data.goods || [{
      name: '-',
      price: '0',
      produced_time: '-',
      sorting: '-',
      quantity: '-',
      remark: '-',
      order_quantity: '',
      allocation: ''
    }],
    total_amount: data.total_amount || ''
  };

  // 构建HTML结构（匹配图片布局）
  let content = `
    <div class="print-title">山东汉达供应链管理有限公司加工单</div>
    
    <!-- 头部信息表格 -->
    <table class="info-section" style="border:0">
      <tr >
        <td width="20%">加工时间：</td>
        <td width="20%" >${getFormattedDate()}</td>
        <td width="15%">购货单位：</td>
        <td width="35%">${safeData.purchaser}</td>
      </tr>
      
    </table>

    <!-- 商品明细表格 -->
    <table class="goods-table">
      <thead>
        <tr>
          <th>商品名称</th>
  				
          <th>加工量</th>
  	<th>出库品类</th>
          <th>出库数</th>
          <th>入库数</th>
          <th>分拣员1</th>
  				<th>分拣员2</th>
        </tr>
      </thead>
      <tbody>
        ${safeData.goods.map(item => `
          <tr>
            <td>${item.name}</td>
            <td>${item.sorting===null ? '':item.sorting}</td>
            <td></td>
        	 <td>${item.out_storage===null ? '':item.out_storage}</td>
            <td>${item.in_storage===null ? '':item.in_storage}</td>
        	<td>${item.fenjian1===null ? '':item.fenjian1}</td>
            <td>${item.fenjian2===null ? '':item.fenjian2}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>

    <!-- 金额汇总 -->
    

    <!-- 签收区域 -->
    <div class="signature-area">
      <div width="35%">
        <p>分拣员：</p>
        
      </div>
      <div>
        <p>验收人：</p>
      </div>
    </div>
  `;

  printWindow.document.write(styles + content);
  printWindow.document.close();

  // 打印处理
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    setTimeout(() => printWindow.close(), 500);
  }
  })
}
function getFormattedDate() {
  const date = new Date();
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}
function formatDate(date) {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  // 补零逻辑（若需要02月格式可启用）
  // const monthPad = String(month).padStart(2, '0');
  return `${year}年${month}月${day}日`;
}
function print2bak2(data) {
  /*if (!data.length) {
    return layer.tips("当前表格无数据", this, { tips: 3 });
  }*/

  const printWindow = window.open("about:blank", "_blank");
  const styles = `
    <style>
      body { font-size: 12px; color: #000; }
      table { width: 100%; border-collapse: collapse; }
      th, td { 
        line-height: 20px; 
        padding: 9px 15px; 
        border: 1px solid #ccc; 
        text-align: left; 
        font-size: 12px; 
      }
      .layui-hide { display: none; }
    </style>
  `;

  // 过滤掉不可打印的列
  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
  
  if(data.purchaser==null){ data.purchaser=''}
  if(data.delivery_time==null){ data.delivery_time=''}
  if(data.user==null){ data.user=''}
  if(data.phone==null){ data.phone=''}
  if(data.address==null){ data.address=''}
  if(data.remark==null){ data.remark=''}
  if(data.name==null){ data.name=''}
  if(data.produced_time==null){ data.produced_time=''}
  if(data.sorting==null){ data.sorting=''}
  if(data.sorting_admin==null){ data.sorting_admin=''}
  if(data.delivery_admin==null){ data.delivery_admin=''}

  // 生成表头
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  tableContent+='<tr><td class="tr-td-left">收货单位</td><td>'+data.purchaser+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">配送日期</td><td>'+data.delivery_time+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人</td><td>'+data.user+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人电话</td><td>'+data.phone+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">收货人地址</td><td>'+data.address+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">备注</td><td>'+data.remark+'</td></tr>'
  tableContent+='<tr><td colspan="2"></td></tr>'


  tableContent+='<tr><td class="tr-td-left">食品名称</td><td>'+data.name+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">规格</td><td>'+data.name+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">生产日期</td><td>'+data.produced_time+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">分拣量</td><td>'+data.sorting+'斤</td></tr>'
  tableContent+='<tr><td class="tr-td-left">分拣员</td><td>'+data.sorting_admin+'</td></tr>'
  tableContent+='<tr><td class="tr-td-left">配送员</td><td>'+data.delivery_admin+'</td></tr></table>'
  


  printWindow.document.write(styles + tableContent);
  printWindow.document.close();

  // 处理浏览器兼容性
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    printWindow.close();
  }
}
function print2bak(data) {
  /*if (!data.length) {
    return layer.tips("当前表格无数据", this, { tips: 3 });
  }*/

  const printWindow = window.open("about:blank", "_blank");
  const styles = `
    <style>
      body { font-size: 12px; color: #5F5F5F; }
      table { width: 100%; border-collapse: collapse; }
      th, td { 
        line-height: 20px; 
        padding: 9px 15px; 
        border: 1px solid #ccc; 
        text-align: left; 
        font-size: 12px; 
      }
      .layui-hide { display: none; }
    </style>
  `;

  // 过滤掉不可打印的列
  const printableCols = layui.pageTable.config.cols[0].filter(col => col.printable !== false);
  
  // 生成表头
  let tableContent = '<div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div><table>';
  /*tableContent += '<thead><tr>';
  printableCols.forEach(col => {
    tableContent += `<th>${col.title}</th>`;
  });
  tableContent += '</tr></thead>';

  // 生成表格数据
  tableContent += '<tbody>';
  data.forEach(item => {
    tableContent += '<tr>';
    printableCols.forEach(col => {
      tableContent += `<td>${item[col.field]}</td>`;
    });
    //tableContent += '<tr><td><td></tr>'
    tableContent += '</tr>';
  });
  tableContent += '</tbody></table>';*/


  printWindow.document.write(styles + tableContent);
  printWindow.document.close();

  // 处理浏览器兼容性
  if (layui.device("edg").edg) {
    printWindow.onafterprint = printWindow.close;
    printWindow.print();
  } else {
    printWindow.print();
    printWindow.close();
  }
}
		function logo(){
			return '';
		}

		function printCustomColumns2(data) {
		  // ✅ 安全获取列配置（优先缓存，次优初始化参数）
		  const cacheCols = layui.table.cache.order?.[0]?.columns || [];
		  const initCols = layui.table.config.order?.init?.cols?.[0] || [];
		  const cols = cacheCols.length ? cacheCols : initCols;
		  //const cols = layui.table.config.order?.init?.cols?.[0] || [];

		  // ✅ 打印字段定义
		  const printFields = [ 'id','nianji', 'name', 'specification', 'delivery_time'];
		  const titleMap = {
		  	  id:'编号',
			  nianji: '县区',
			  name: '商品名称',
			  specification: '规格',
			  delivery_time: '配送时间'
			};
		  /*const headers = printFields.map(field => {
		    const col = cols.find(c => c.field === field);
		    return `<th>${col?.title || field}</th>`; // 自动适配中文标题
		  }).join('');*/
		  // ✅ 生成表头
		  /*const headers = printFields.map(field => {
		  const colConfig = cols.find(c => c.field === field);
		  return `<th width="${colConfig?.width || 100}">${titleMap[field] || field}</th>`;
			}).join('');*/
		  const headers = printFields.map(title => {
		    const colConfig = cols.find(c => c.title === title);
		    return `<th width="${colConfig?.width || 100}">${colConfig?.title  || title}</th>`;
		  }).join('');
		  /*const headers = printFields.map(field => {
		    const colConfig = cols.find(c => c.field === field);
		    return `<th width="${colConfig?.width || 100}">${colConfig?.title || field}</th>`;
		  }).join('');*/

		  // ✅ 构建数据行（兼容空数据）
		  const rows = (data || []).map(item => `
		    <tr>
		      ${printFields.map(field => `<td>${item[field] || ''}</td>`).join('')}
		    </tr>
		  `).join('');

		  // ✅ 生成打印内容
		  const printHtml = `
		    <style>
		    	 @media print {
		        @page { margin: 0; }
		        body { margin: 2cm; }
		        .print-title { font-size: 24px; text-align: center; margin-bottom: 20px; }
		        .layui-table { width: 100%; border-collapse: collapse; }
		        .layui-table th, 
		        .layui-table td { 
		          border: 1px solid #666; 
		          padding: 8px;
		          text-align: center;
		          font-size: 14px;
		        }
		      }
		    </style>
		    <div class="custom-print-title" style="text-align:center;font-size:30px;margin-bottom:50px">山东汉达供应链管理有限公司销货单</div>
		    <table class="layui-table>
		      <tbody><tr>${headers}</tr></tbody>
		      <tbody>${rows}</tbody>
		    </table>
		  `;
		  /*const printHtml = `
		    <style></style>
		    <div class="custom-print-title">订单表打印报表</div>
		    <table class="layui-table custom-print-table">
		      <thead><tr>${headers}</tr></thead>
		      <tbody>${rows}</tbody>
		    </table>
		  `;*/
		  // ✅ 安全打印
		  const printWindow = window.open('', '_blank');
		  if (printWindow) {
		    printWindow.document.write(printHtml);
		    printWindow.document.close();
		    printWindow.print();
		    printWindow.close();
		  } else {
		    layer.msg('浏览器阻止了弹窗，请允许后重试', {icon: 2});
		  }
		}

	}
</script>
{/block}
<!-- /脚本 -->